package com.ticket.sass.admin.manager

import com.ticket.sass.common.exception.enums.ErrorCode
import com.ticket.sass.common.exception.exception.InternalException
import com.ticket.sass.common.ticketserver.format
import org.redisson.api.RMapCache
import org.redisson.api.RedissonClient
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.util.concurrent.TimeUnit


/**
 * 编码生成器
 *
 * @author 朱其鹏
 * @date 2024/3/27 15:44
 */
@Component
class GeneratorCodeManager(
    private val redissonClient: RedissonClient
) {

    private val mapCache: RMapCache<String, Any>
        get() {
            return redissonClient.getMapCache("TicketSassApiGeneratorCodeManager")
        }

    /**
     * 订单编号
     *
     * 格式：日期+盐+随机数
     */
    fun orderNo(salt: String = ""): String {
        for (i in 0 .. 899999) {
            val dateTimeFormat = LocalDateTime.now().format("yyyyMMddHHmmss")
            val rand = (100000 until 999999).random()
            val number = "${dateTimeFormat}${salt}${rand}"
            val cacheKey = "generateOrderNo:$number"

            if (mapCache[cacheKey] != null) {
                continue
            } else {
                mapCache.put(cacheKey, number, 20, TimeUnit.SECONDS)

                return number
            }
        }

        throw InternalException(ErrorCode.SERVER_ERROR, "每秒生成订单编号达到上限")
    }
}